package com.hyf.zookeeper.core;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

public class ZKGetData {

    private static ZooKeeper zk;

    private static ZookeeperConnection zkConn;

    public static Stat znode_exists(String path) throws KeeperException, InterruptedException {
        return zk.exists(path,true);
    }

    public static void main(String[] args){
        final String path="/MyFirstZnode2";

        final CountDownLatch connectSignal=new CountDownLatch(1);
        zkConn=new ZookeeperConnection();
        try {
            zk=zkConn.connect("47.93.157.178:12181");
            Stat stat = znode_exists(path);
            if(stat!=null){
                System.out.println("Node  exists and the node version is:"+stat.getVersion());
                byte[] b=zk.getData(path, new Watcher() {
                    public void process(WatchedEvent watchedEvent) {
                        if(watchedEvent.getType()==Event.EventType.None){
                            if(watchedEvent.getState()==Event.KeeperState.Expired)
                                connectSignal.countDown();
                        }else{
                            byte[] bn= new byte[0];
                            try {
                                bn = zk.getData(path,false,null);
                                String data=new String(bn,"utf-8");
                                System.out.println("2data:"+data);
                                connectSignal.countDown();
                            } catch (KeeperException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                },null);
                String data=new String(b,"utf-8");
                System.out.println("1ata:"+data);
                connectSignal.await();
            }else{
                System.out.println("Node does not exists");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }
}
